package com.moonshineproject.plugin.console
{
	import com.moonshineproject.GlobalEventDispatcher;
	import com.moonshineproject.text.TextLineModel;
	import com.moonshineproject.utils.HtmlFormatter;
	import no.doomsday.console.ConsoleUtil;
	
	import flash.events.EventDispatcher;
	
	public class ConsoleOutputter extends EventDispatcher
	{
		public static var DEBUG:Boolean = false;
		
		protected var _name:String = "";
		public function get name():String
		{
			return _name;
		}
		
		// Console output functions, use %s for substitution
		protected function notice(str:String, ...replacements):void
		{
			formatOutput(HtmlFormatter.sprintfa(str, replacements), 'notice');
		}
		
		protected function error(str:String, ...replacements):void
		{
			formatOutput(HtmlFormatter.sprintfa(str, replacements), 'error');
		}
		
		protected function warning(str:String, ...replacements):void
		{
			formatOutput(HtmlFormatter.sprintfa(str, replacements), 'warning');
		}
		
		protected function print(str:String, ...replacements):void 
		{
			ConsoleUtil.print(str);
			formatOutput(HtmlFormatter.sprintfa(str, replacements), 'weak');
		}
		
		protected function debug(str:String, ...replacements):void
		{
			if (DEBUG)
			{
				formatOutput(HtmlFormatter.sprintfa(str, replacements), 'weak');
			}
		}

		
		private function formatOutput(str:String, style:String):void
		{
			var textLines:Array = str.split("\n");
			var lines:Vector.<TextLineModel> = Vector.<TextLineModel>([]);
			for (var i:int = 0; i < textLines.length; i++)
			{
				if (textLines[i] == "") continue;
				var text:String = HtmlFormatter.sprintf("<%x>%x:</%x> %x", style, name, style, textLines[i]); 
				var lineModel:TextLineModel = new MarkupTextLineModel(text);
				lines.push(lineModel);
			}
			outputMsg(lines);
		}
		
		protected function outputMsg(msg:*):void 
		{
			GlobalEventDispatcher.getInstance().dispatchEvent(new ConsoleOutputEvent(msg));
		}
		
		protected function clearOutput():void 
		{
			GlobalEventDispatcher.getInstance().dispatchEvent(new ConsoleOutputEvent("", true));
		}

	}
}